package com.example.zhanghao.controller;

import com.example.zhanghao.VO.CommonVo;
import com.example.zhanghao.services.CaptchaService;
import com.google.code.kaptcha.Producer;
import org.apache.tomcat.util.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController //这是返回接口
@RequestMapping("/captcha")
public class CaptchaController {
    private static final Logger LOG = LoggerFactory.getLogger(CaptchaController.class);

    @Autowired
    private Producer kaptchaProducer;

    @Autowired
    private CaptchaService captchaService;

    @GetMapping("/image")
    public CommonVo getImageCaptcha(HttpServletResponse response, HttpServletRequest request) throws IOException {
        // 清除浏览器缓存
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");

        // 创建验证码文本
        String capText = kaptchaProducer.createText();


        LOG.info(capText);

        // 获取会话ID
        String sessionId = request.getSession().getId();

        LOG.info(sessionId);

        // 存储验证码
        captchaService.storeCaptcha( sessionId, capText);

        // 创建验证码图片
        BufferedImage image = kaptchaProducer.createImage(capText);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        // 输出图片
        ImageIO.write(image, "jpg", outputStream);
        String base64Code = "";
        base64Code = Base64.encodeBase64String(outputStream.toByteArray());

        CommonVo<Object> commonResp = new CommonVo<>();

        Map<String, String> map = new HashMap<>();
        map.put("img", "data:image/png;base64," + base64Code);
        map.put("sessionId", sessionId);
        commonResp.setData(map);
        return commonResp;
    }

}

